package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.enums.RedisEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.Cacheable;
import com.qk.vo.portal.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class CacheableAspect {

    @Autowired
    private StringRedisTemplate redisClient;



    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        String redisKey = null;
        long expireTime = 0;
        TimeUnit expireeTimeUnit = null;
        String jsonStr = null;
        try {

            Cacheable annotation = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName()).getAnnotation(Cacheable.class);
            redisKey = annotation.keyPrefix() + annotation.Key();
            expireTime = annotation.expireTime();
            expireeTimeUnit = annotation.expireTimeUnit();

            jsonStr = redisClient.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(jsonStr)){
                return JSONUtil.toBean(jsonStr, pjp.getTarget().getClass().getMethod(pjp.getSignature().getName()).getReturnType());
            }
        } catch (Exception e) {
            log.error("redis缓存获取失败：{}", e.getMessage());
        }

        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            log.error("操作异常：{}", e.getMessage());
            CommonException.throwCommonException(ParamEnum.OPERATION_ERROR);
        }

        try {
            redisClient.opsForValue().set(redisKey, JSONUtil.toJsonStr(proceed),expireTime,expireeTimeUnit);
        } catch (Exception e) {
            log.error("redis缓存写入失败：{}", e.getMessage());
        }
        return proceed;
    }
}
